<?php

namespace Home\Controller;

use Think\Controller;

class OrderController extends BaseController {

    /**
     * @desc: 批量入库(“编号是否重复”可选)
     * @Author: xushu
     * @again quyang 2017-07-25
     * */
    public function PacketsavedSwitch()
    {
        $param = I('param.');
        $repeatSwitch = D('Home/User') -> where(array('f_user_id' => $param['stationId'])) -> getField('f_packetnum_repeat');

        // $repeatSwitch  1 编号可重复  2 编号不可重复
        if ($repeatSwitch == 1)
        {
            // 批量入库，包裹编号不重复
            $this -> batchSavePacket();
        }
        elseif($repeatSwitch == 2)
        {
            // 批量入库，包裹编号可重复
            $this -> batchSavePacketOnStorage_bak();
        }
    }

    /**
     * @desc: 批量入库
     * @Author: delayhsiao
     * @again quyang 2017-1-21
     * @update: 2016-11-22
     * */
    public function batchSavePacket() {
        $data = I('param.');
        if (empty($data['stationId']) || empty($data['companyId']) || empty($data['companyName']) || $data['source'] == '' || $data['outWay'] == '' || $data['outSource'] == '' || empty($data['packetInfo'])) {
            $this->param_error(false);
        }

        $pregMobile = '/^[1][34578]\d{9}$/';
        $par = "/[\x80-\xff]/";
        $packetInfo = rtrim($data['packetInfo'], ',');

        $packetsArr = json_decode(htmlspecialchars_decode($packetInfo), true);
        //根据运单号去重
        $packetsArr_info = $this->getArrayUniqueByKeys($packetsArr);

        //验证用户下短信余额
        $balance = D('Home/User')->where(array('f_user_id' => $data['stationId']))->getField('f_buy_count');

        if ($balance < count($packetsArr_info)) {
            $this->auto_error('站点短信余额不足, 无法入库');
        }

        foreach ($packetsArr_info as $k => $v) {
            if (!preg_match("/^[a-zA-Z0-9]{1}[a-zA-Z0-9\-]{7,23}$/", $v['mailNo'])) {
                $this->auto_error('运单号错误');
            }
            if (!preg_match($pregMobile, $v['mobile'])) {
                $this->auto_error('手机号错误');
            }
            if (preg_match($par, $v['mailNo'])) {
                $this->auto_error('运单号不能为中文');
            }

            //编号不允许为空  2017-03-04
            if (!preg_match("/^[0-9]{1,6}$/", $v['num'])) {
                $this->auto_error('请填写1-6位纯数字编号');
            }

            if (8 > strlen($v['mailNo']) || strlen($v['mailNo']) > 24)
                $this->auto_error('运单号长度错误');

            //获取手机号
            $mobile_data[] = $v['mobile'];

            //获取运单号
            $mail_data[] = $v['mailNo'];

            //get参数
            $getData = I('get.');

            $packets[] = array(
                'f_station_id' => $data['stationId'],
                'f_mail_no' => $v['mailNo'],
                'f_company_id' => $data['companyId'],
                'f_company_name' => $data['companyName'],
                'f_recipient_mobile' => $v['mobile'],
                'f_recipient_name' => empty($v['name']) ? '' : $v['name'],
                'f_frame_code' => empty($v['frameCode']) ? '' : $v['frameCode'],
                'f_num' => $v['num'],
                'f_input_way' => 1,
                'f_input_source' => intval($data['source']),
                'f_parcel_status' => 2,
                'f_out_way' => $data['outWay'],
                'f_out_source' => $data['outSource'],
                'f_exp_id' => empty($data['fExpId']) ? '0' : $data['fExpId'],
                'source' => $getData['bmxSource'],
                'version' => $getData['bmxVersion']
            );
        }

        //验证手机号是否加入黑名单
        $Order = new \Home\Server\OrderService();
        $mobile_status = $Order->mobileStatus($data['stationId'], $mobile_data);

        if (is_array($mobile_status[0])) {
            $this->auto_error('手机号:' . $mobile_status[0]['f_recipient_mobile'] . '已被拉黑');
        }

        //验证运单号是否重复   ------ 禁止重复入库 ------
        $parcelService = new \Home\Server\ParcelService();
        $mail_status = $parcelService->MailNO_Repeat($data['stationId'], $mail_data);

        if (is_array($mail_status[0])) {
            $this->auto_error('运单:' . $mail_status[0]['f_mail_no'] . '已存在，请勿重复入库');
        }

        //入库
        $arr = $parcelService->PutStorage($packets, $data['professional']);

        if ($arr['insertResult'] == false && empty($arr['updateResult'])) {
            $this->output(false);
        }

        $this->output(true,array(),'入库成功');
    }

    /**
     * @desc: 批量入库(修改batchSavePacket后，暂时配合上线版本 2017-07-08)
     * @Author: delayhsiao
     * @again quyang 2017-1-21
     * @update: 2016-11-22
     * */
    public function batchSavePacketOnStorage() {
        $data = I('param.');
        if (empty($data['stationId']) || empty($data['companyId']) || empty($data['companyName']) || $data['source'] == '' || $data['outWay'] == '' || $data['outSource'] == '' || empty($data['packetInfo'])) {
            $this->param_error(false);
        }

        $pregMobile = '/^[1][34578]\d{9}$/';
        $par = "/[\x80-\xff]/";
        $packetInfo = rtrim($data['packetInfo'], ',');

        $packetsArr = json_decode(htmlspecialchars_decode($packetInfo), true);

        //根据运单号去重
        $packetsArr_info = $this->getArrayUniqueByKeys($packetsArr);

        //验证用户下短信余额
        $balance = D('Home/User')->where(array('f_user_id' => $data['stationId']))->getField('f_buy_count');

        if ($balance < count($packetsArr_info)) {
            $this->auto_error('站点短信余额不足, 无法入库');
        }

        foreach ($packetsArr_info as $k => $v) {
            if (!preg_match("/^[a-zA-Z0-9]{1}[a-zA-Z0-9\-]{7,23}$/", $v['mailNo'])) {
                $this->auto_error('运单号错误');
            }
            if (!preg_match($pregMobile, $v['mobile'])) {
                $this->auto_error('手机号错误');
            }
            if (preg_match($par, $v['mailNo'])) {
                $this->auto_error('运单号不能为中文');
            }

            //编号不允许为空  2017-03-04
            if (!preg_match("/^[0-9]{1,6}$/", $v['num'])) {
                $this->auto_error('请填写1-6位纯数字编号');
            }

            if (8 > strlen($v['mailNo']) || strlen($v['mailNo']) > 24)
                $this->auto_error('运单号长度错误');

            //获取手机号
            $mobile_data[] = $v['mobile'];

            //获取运单号
            $mail_data[] = $v['mailNo'];

            //get参数
            $getData = I('get.');

            $packets[] = array(
                'f_station_id' => $data['stationId'],
                'f_mail_no' => $v['mailNo'],
                'f_company_id' => $data['companyId'],
                'f_company_name' => $data['companyName'],
                'f_recipient_mobile' => $v['mobile'],
                'f_recipient_name' => empty($v['name']) ? '' : $v['name'],
                'f_frame_code' => empty($v['frameCode']) ? '' : $v['frameCode'],
                'f_num' => $v['num'],
                'f_input_way' => 1,
                'f_input_source' => intval($data['source']),
                'f_parcel_status' => 2,
                'f_out_way' => $data['outWay'],
                'f_out_source' => $data['outSource'],
                'f_exp_id' => empty($data['fExpId']) ? '0' : $data['fExpId'],
                'source' => $getData['bmxSource'],
                'version' => $getData['bmxVersion']
            );
        }

        //验证手机号是否加入黑名单
        $Order = new \Home\Server\OrderService();
        $mobile_status = $Order->mobileStatus($data['stationId'], $mobile_data);

        if (is_array($mobile_status[0])) {
            $this->auto_error('手机号:' . $mobile_status[0]['f_recipient_mobile'] . '已被拉黑');
        }

        //验证运单号是否重复   ------ 禁止重复入库 ------
        $parcelService = new \Home\Server\ParcelService();
        $mail_status = $parcelService->MailNO_Repeat($data['stationId'], $mail_data);

        if (is_array($mail_status[0])) {
            $this->auto_error('运单:' . $mail_status[0]['f_mail_no'] . '已存在，请勿重复入库');
        }

        //入库
        $arr = $parcelService->PutStorage($packets, $data['professional']);

        if ($arr['insertResult'] == false && empty($arr['updateResult'])) {
            $this->output(false);
        }

        $this->output(true,array(),'入库成功');
    }



    /**
     * @desc: 批量入库(2017-07-08，接口待商讨)
     * @Author: delayhsiao
     * @again quyang 2017-1-21
     * @update: 2016-11-22
     * */
    public function batchSavePacketOnStorage_bak() {
        $data = I('param.');
        if (empty($data['stationId']) || empty($data['companyId']) || empty($data['companyName']) || $data['source'] == '' || $data['outWay'] == '' || $data['outSource'] == '' || empty($data['packetInfo'])) {
            $this->param_error(false);
        }

        $pregMobile = '/^[1][34578]\d{9}$/';
        $par = "/[\x80-\xff]/";
        $packetInfo = rtrim($data['packetInfo'], ',');

        $packetsArr = json_decode(htmlspecialchars_decode($packetInfo), true);

        //根据运单号去重
        $packetsArr_info = $this->getArrayUniqueByKeys($packetsArr);
        //验证用户下短信余额
        $balance = D('Home/User')->where(array('f_user_id' => $data['stationId']))->getField('f_buy_count');

        if ($balance < count($packetsArr_info)) {
            $this->auto_error('站点短信余额不足, 无法入库');
        }

        // 判断编号是否重复，如果重复放入repeat数组，如果不重复放入available数组
        $parcelService = new \Home\Server\ParcelService();
        $resultArr = $parcelService -> FrameCodeNum_Repeat( $data['stationId'] ,$packetsArr_info );
//        var_dump($resultArr);die;

        // 如果没有“可储存的数据”，返回原数组
        if (count($resultArr['available']) < 1)
        {
            $this->output(true, $resultArr['repeat']);
        }

        foreach ($resultArr['available'] as $k => $v) {
            if (!preg_match("/^[a-zA-Z0-9]{1}[a-zA-Z0-9\-]{7,23}$/", $v['mailNo'])) {
                $this->auto_error('运单号错误');
            }
            if (!preg_match($pregMobile, $v['mobile'])) {
                $this->auto_error('手机号错误');
            }
            if (preg_match($par, $v['mailNo'])) {
                $this->auto_error('运单号不能为中文');
            }

            //编号不允许为空  2017-03-04
            if (!preg_match("/^[0-9]{1,6}$/", $v['num'])) {
                $this->auto_error('请填写1-6位纯数字编号');
            }

            if (8 > strlen($v['mailNo']) || strlen($v['mailNo']) > 24)
                $this->auto_error('运单号长度错误');

            //获取手机号
            $mobile_data[] = $v['mobile'];

            //获取运单号
            $mail_data[] = $v['mailNo'];

            //get参数
            $getData = I('get.');

            $packets[] = array(
                'f_station_id' => $data['stationId'],
                'f_mail_no' => $v['mailNo'],
                'f_company_id' => $data['companyId'],
                'f_company_name' => $data['companyName'],
                'f_recipient_mobile' => $v['mobile'],
                'f_recipient_name' => empty($v['name']) ? '' : $v['name'],
                'f_frame_code' => empty($v['frameCode']) ? '' : $v['frameCode'],
                'f_num' => $v['num'],
                'f_input_way' => 1,
                'f_input_source' => intval($data['source']),
                'f_parcel_status' => 2,
                'f_out_way' => $data['outWay'],
                'f_out_source' => $data['outSource'],
                'f_exp_id' => empty($data['fExpId']) ? '0' : $data['fExpId'],
                'source' => $getData['bmxSource'],
                'version' => $getData['bmxVersion']
            );
        }

        //验证手机号是否加入黑名单
        $Order = new \Home\Server\OrderService();
        $mobile_status = $Order->mobileStatus($data['stationId'], $mobile_data);

        if (is_array($mobile_status[0])) {
            $this->auto_error('手机号:' . $mobile_status[0]['f_recipient_mobile'] . '已被拉黑');
        }

        //验证运单号是否重复   ------ 禁止重复入库 ------
        $parcelService = new \Home\Server\ParcelService();
        $mail_status = $parcelService->MailNO_Repeat($data['stationId'], $mail_data);

        if (is_array($mail_status[0])) {
            $this->auto_error('运单:' . $mail_status[0]['f_mail_no'] . '已存在，请勿重复入库');
        }

        //入库
        $arr = $parcelService->PutStorage($packets, $data['professional']);

        if ($arr['insertResult'] == false && empty($arr['updateResult'])) {
            $this->output(false);
        }

        $this->output(true, $resultArr['repeat'] ,'入库成功');
    }



    /**
     * Function getArrayUniqueByKeys
     * @param $arr
     * @return mixed
     *
     * Author: quyang
     * Date: 2017-2-13 15:18
     * Info: 运单号去重
     */
    public function getArrayUniqueByKeys($arr) {

        $arr_out = array();
        foreach ($arr as $k => $v) {
            $key_out = $v['mailNo'] . "-" . $v['age']; //提取内部一维数组的key(name age)作为外部数组的键

            if (array_key_exists($key_out, $arr_out)) {
                continue;
            } else {
                $arr_out[$key_out] = $arr[$k]; //以key_out作为外部数组的键
                $arr_wish[$k] = $arr[$k];  //实现二维数组唯一性
            }
        }
        return $arr_wish;
    }

    /**
     * @desc:  扫件入库
     * @Author: zhoutai
     * @again quyang 2017-1-21
     * @update: 16/11/22
     * */
    public function savePacket() {
        $data = I('param.');
        if (empty($data['stationId']) || empty($data['mailNo']) || $data['packetType'] != '0' || empty($data['frameCode']) || empty($data['mobile']) || empty($data['name']) || $data['source'] == '' || empty($data['num']) || $data['outWay'] == '' || $data['outSource'] == '' || empty($data['companyId']) || empty($data['companyName'])) {
            $this->param_error();
        }

        //验证用户下短信余额
        $balance = D('Home/User')->where(array('f_user_id' => $data['stationId']))->getField('f_buy_count');

        if ($balance < 1) {
            $this->auto_error('短信余额不足');
        }

        $pregMobile = '/^[1][34578]\d{9}$/';
        $par = "/[\x80-\xff]/";
        if (!preg_match("/^[a-zA-Z0-9]{1}[a-zA-Z0-9\-]{7,23}$/", $data['mailNo'])) {
            $this->auto_error('运单号错误');
        }
        if (!preg_match($pregMobile, $data['mobile'])) {
            $this->auto_error('手机号错误');
        }
        if (preg_match($par, $data['mailNo'])) {
            $this->auto_error('运单号不能为中文');
        }
        if (strlen($data['mailNo']) < 8 || strlen($data['mailNo']) > 24) {
            $this->auto_error('运单号长度错误');
        }
        if ($data['source'] == '4') {
            $expressBranch = D('tp_express_branch_com_dz');
            $verify = $expressBranch->where(array('f_station_id' => $data['stationId']))->find();
            if (empty($verify)) {
                $this->output(0);
            }
        }

        //                      ------------验证编号是否重复---------------
        $packetInfo_arr[] = array(
            'mailNo' => $data['mailNo'],
            'mobile' => $data['mobile'],
            'num' => $data['num'],
            'name' => $data['name'],
            'frameCode' => $data['frameCode']
        );

        $parcelService = new \Home\Server\ParcelService();
        $resultArr = $parcelService -> FrameCodeNum_Repeat($data['stationId'],$packetInfo_arr);

        if (count($resultArr['repeat']) > 0)
        {
            $this->auto_error('编号:' . $data['frameCode'] . $data['num'] . '已存在');
        }

        //get参数
        $getData = I('get.');

        $parcelData = array(
            'f_frame_code' => $data['frameCode'],
            'f_mail_no' => $data['mailNo'],
            'f_num' => $data['num'],
            'f_out_source' => $data['outSource'],
            'f_out_way' => $data['outWay'],
            'f_type' => $data['packetType'],
            'f_company_id' => $data['companyId'],
            'f_company_name' => $data['companyName'],
            'f_recipient_name' => $data['name'],
            'f_recipient_mobile' => $data['mobile'],
            'f_input_way' => '0',
            'f_input_source' => '1',
            'f_station_id' => $data['stationId'],
            'f_parcel_status' => 2,
            'f_weixin_notice_status' => '0',
            'f_app_notice_status' => '0',
            'f_sms_notice_status' => '0',
            'f_is_detention' => '0',
            'source' => $getData['bmxSource'],
            'version' => $getData['bmxVersion']
        );

        //f_weixin_notice_status  f_app_notice_status   f_sms_notice_status  无用字段下版本删除
        !empty($data['fExpId']) && $parcelData['f_exp_id'] = $data['fExpId'];

        //验证手机号是否加入黑名单
        $Order = new \Home\Server\OrderService();
        $mobile_status = $Order->mobileStatus($data['stationId'], $data['mobile']);

        if (is_array($mobile_status[0])) {
            $this->auto_error('手机号:' . $mobile_status[0]['f_recipient_mobile'] . '已被拉黑');
        }

        //验证运单号是否重复   ------ 禁止重复入库 ------
        $parcelService = new \Home\Server\ParcelService();
        $mail_status = $parcelService->MailNO_Repeat($data['stationId'], [$data['mailNo']]);

        if (is_array($mail_status[0])) {
            $this->auto_error('运单:' . $mail_status[0]['f_mail_no'] . '已存在，请勿重复入库');
        }

        //入库
        $parcelService = new \Home\Server\ParcelService();
        $arr = $parcelService->PutStorage($parcelData);

        if ($arr['insertResult'] == false && empty($arr['updateResult'])) {
            $this->output(false);
        }
        if (!empty($arr['updateResult'])) {
            foreach ($arr['updateResult'] as $new_data) {
                if ($new_data['updateResult'] == 0) {
                    $this->auto_error('更新包裹失败');
                }
                $this->updateData($new_data);
            }
        }
        $this->output(true, array());
    }

    /**
     * @desc:  队列存在任务就更新
     * @Author: zhoutai
     * @update: 16/12/11
     * */
    private function updateData($parcelInfo) {

        $noticeServer = new \Home\Server\ParcelNoticeResultServer();
        $count = $noticeServer->countParcelNotice($parcelInfo['f_parcel_id'], "f_parcel_id");

        if ($count['count'] > 0) {

            $update = array(
                'f_take_code' => $parcelInfo['f_take_code'],
                'f_recipient_mobile' => $parcelInfo['f_recipient_mobile'],
                'f_recipient_name' => $parcelInfo['f_recipient_name'],
                'f_weixin_notice' => 0,
                'f_weixin_num' => 0,
                'f_sms_notice' => 0,
                'f_sms_num' => 0,
                'f_create_time' => date('YmdHis'),
                'f_create_time_stamp' => time(),
                'f_weixin_send_time' => '',
                'f_weixin_send_time_stamp' => 0,
                'f_weixin_success_time' => '',
                'f_weixin_success_time_stamp' => 0,
                'f_sms_success_time' => '',
                'f_sms_success_time_stamp' => 0,
                'f_sms_error' => '',
                'f_sms_send_time' => '',
                'f_sms_send_time_stamp' => 0
            );

            $noticeServer->updateParcelNotice($parcelInfo['f_parcel_id'], $update);
        }
    }

    /**
     * @desc:   根据手机号查找姓名
     * @Author: zhoutai
     * @update: 16/11/22
     * */
    public function queryReceiverNameByMobile() {
        $data = I('param.');
        if (empty($data['mobile'])) {
            $this->param_error();
        }
        $recipient = D('tp_recipient_info')->where(array('f_mobile' => $data['mobile']))->field('f_name as receiverName, f_mobile as receiverMobile')->find();
        empty($recipient) ? $this->output(1) : $this->output(1, $recipient);
    }

    /**
     * @desc:  查询多状态包裹
     * @Author: zhoutai
     * @again quyang 2017-1-21
     * @update: 16/11/23
     * */
    public function queryPacketList() {
        $data = I('param.');

        if (empty($data['stationId']) || $data['packetType'] == '') {
            $this->param_error();
        }
        if (empty($data['mobile'])) {
            $data['mobile'] = '';
        }

        //时间筛选为空、通知中和通知失败的时候默认搜索两个月的数据
        //防止出现每月一号数据异常
        if (empty($data['beginDate']) || $data['packetType'] == 2 || $data['packetType'] == 5) {

            $startTime = date('Y-m-01', strtotime("-1 month"));
            $endTime = date('Y-m-d');
        }

        $mobile = $mailNO = '';

        //运单号搜索  2017-05-08
        if (preg_match('/^[1][34578]\d{9}$/', $data['mobile'])) {
            $mobile = $data['mobile'];
        } else {
            $mailNO = $data['mobile'];
        }


        $parcelService = new \Home\Server\ParcelService();
        //总数量
        $count = $parcelService->countConditionStorage($data['stationId'], $mobile, $data['beginDate'], $data['packetType'], $data['fCompanyId'], $mailNO, '', $startTime, $endTime);

        //查询通知中和通知失败的数据
        //通知中、通知失败结果不受条件限制
        $noticeIng = $parcelService->countConditionStorage($data['stationId'], 0, '', 2, '', '', '', date('Y-m-01', strtotime("-1 month")), date('Y-m-d'));
        $noticeFail = $parcelService->countConditionStorage($data['stationId'], 0, '', 5, '', '', '', date('Y-m-01', strtotime("-1 month")), date('Y-m-d'));

        $page = !empty($data['currentPage']) ? $data['currentPage'] : 1;

        //兼容错误的APP参数
        if (strpos($data['currentPage'], 'Optional') !== False) {
            $page = substr($data['currentPage'], 9, -1);
        }

        $pageSize = !empty($data['pageSize']) ? $data['pageSize'] : 20;
        $totalPages = ceil($count / $pageSize);

        //查询数据
        $packetList = $parcelService->getConditionStorage($data['stationId'], $mobile, $data['beginDate'], $data['packetType'], $page, $pageSize, $data['fCompanyId'], $mailNO, '', $startTime, $endTime);


        $noticeIng == false ? $noticeIng = '0' : $noticeIng;
        $noticeFail == false ? $noticeFail = '0' : $noticeFail;

        $result = array(
            'count' => $count,
            'noticeIng' => $noticeIng,
            'noticeFail' => $noticeFail,
            'pcketinfo' => $packetList,
            'totlePage' => $totalPages
        );
        $this->output(true, $result);
    }


    public function packetsStatistics()
    {
        $data = I('param.');

        // 必须参数校验
        if (empty($data['stationId']) || $data['packetType'] == '' || $data['noticeType'] == '') {
            $this->param_error();
        }

        // 运单号、包裹编号、手机号校验
        if (!empty($data['mobile']))
        {
            if (preg_match("/^[1][34578]\d{9}$/" ,$data['mobile']))
            {
                $mobile = $data['mobile'];
            }
            elseif (preg_match("/^[0-9]{1,6}$/" ,$data['mobile']))
            {
                $num = $data['mobile'];
            }
            else
            {
                $mailNo = $data['mobile'];
            }
        }


        // 时间参数校验
        if (empty($data['beginDate']))
        {
            $startTime = date('Y-m-01', strtotime("-1 month"));
        }
        else
        {
            $startTime = $data['beginDate'];
        }

        if (empty($data['endDate']))
        {
            $endTime = date('Y-m-d');
        }
        else
        {
            $endTime = $data['endDate'];
        }

        // 包裹状态与通知状态参数校验
        if($data['packetType'] == '-250'  )
        {
            $type = $data['noticeType'];
        }
        else
        {
            $type = $data['packetType'];
        }

        // 总数量
        $parcelService = new \Home\Server\ParcelService();

        $count = $parcelService->countConditionStorage($data['stationId'], $mobile, $data['beginDate'], $type, $data['companyId'], $mailNo, '', $startTime, $endTime, '' ,$num);

        $page = !empty($data['currentPage']) ? $data['currentPage'] : 1;

        //兼容错误的APP参数
        if (strpos($data['currentPage'], 'Optional') !== False) {
            $page = substr($data['currentPage'], 9, -1);
        }

        $pageSize = !empty($data['pageSize']) ? $data['pageSize'] : 20;
        $totalPages = ceil($count / $pageSize);

        //查询数据
        $packetList = $parcelService->getConditionStorage($data['stationId'], $mobile, $data['beginDate'], $type, $page, $pageSize, $data['companyId'], $mailNo, '', $startTime, $endTime, '', $num);

        // 获取微信、短信通知状态
        $result = array(
            'count' => $count,
            'pcketinfo' => $packetList,
            'totlePage' => $totalPages
        );

        $this->output(true, $result);

    }

    /**
     * 获取滞留件列表(或重发短信、微信)
     */
    public function queryRetentionPacketList()
    {
        $data = I('param.');

        if (empty($data['stationId'])) {
            $this->param_error('参数错误');
        }

        if (empty($data['mobile'])) {
            $data['mobile'] = '';
        }

        if ( empty($data['packetType']))
        {
            $data['packetType'] = 0;
        }

        $page = !empty($data['currentPage']) ? $data['currentPage'] : 1;

        //兼容错误的APP参数
        if (strpos($data['currentPage'], 'Optional') !== False) {
            $page = substr($data['currentPage'], 9, -1);
        }

        // 滞留时间参数
        $time = $this->getRetentionTime($data['retentionTime']);


        //运单号搜索  2017-07-19
        if (preg_match('/^[1][34578]\d{9}$/', $data['mobile'])) {
            $mobile = $data['mobile'];
        } else {
            $mailNO = $data['mobile'];
        }

        $parcelService = new \Home\Server\ParcelService();

        // 重新通知方法：0 只获取数据；1 微信通知；2 短信通知 ；
        if ($data['resendType'] == '' || $data['resendType'] == 0)
        {
            // 计算滞留件数量
            $count = $parcelService->countRetentionStorage($data['stationId'], $mobile, '', $data['packetType'], '', $mailNO, '', $time['startTime'], $time['endTime'], '', $data['noticeWay']);

            $pageSize = !empty($data['pageSize']) ? $data['pageSize'] : 20;
            $totalPages = ceil($count / $pageSize);

            //查询滞留件数据
            $packetList = $parcelService->getRetentionStorage($data['stationId'], $mobile, '', $data['packetType'], $page, $pageSize, '', $mailNO, '', $time['startTime'], $time['endTime'], '', $data['noticeWay']);

            $result = array(
                'count' => $count,
                'pcketinfo' => $packetList,
                'totlePage' => $totalPages
            );

            $this->output(true, $result);

        } // 微信通知
        elseif ($data['resendType'] == 1) {
            // 获取所有滞留件
            $packetList = $parcelService->getAllRetentionStorage($data['stationId'], $data['packetType'], $time['startTime'], $time['endTime'], $data['noticeWay'] ,$mobile , $mailNO);

            foreach ($packetList as $k => $v) {
                $codeData = $v['f_take_code'];

                //如果是专业版, 则提货码 变为编号
                if ((new \Home\Server\UserService())->verify_professional($v['f_station_id']) || $v['f_speed_status'] == '2') {
                    //兼容老数据  过后可以弃用
                    $codeData = $v['f_num'] . ' (包裹编号)';
                }

                $fmailNo = $v['f_mail_no'];

                //运单号为空则推送包裹id （极速版运单号为空）
                if ($v['f_mail_no'] == '') {
                    $fmailNo = $v['f_parcel_id'] . '(包裹ID)';
                }

                //发微信并记录发送微信次数，根据返回值修改微信通知状态或成功发送时间
                $data = array(
                    'mobile' => $v['f_recipient_mobile'], //收件人手机号码
                    'name' => $v['f_station_name'],     //站点名称
                    'mailno' => $fmailNo,                  //运单号
                    'code' => $codeData,                //提货码
                    'company' => $v['f_company_name'],     //快递公司名称
                    'address' => $v['f_address'],          //站点地址
                    'qtime' => $v['f_qtime'],            //站点营业时间
                    'remark' => '感谢您的使用',
                    'type' => $v['f_speed_status'],     //入库类型  0.普通版  1.专业版  2.极速版  2017-5-23 quyang
                    'tel' => $v['f_tel']               //站点的联系电话
                );
                $return_weixin = send_weixin($data);
                $arr_weixin = json_decode($return_weixin, true);

                $Notice = new \Home\Server\ParcelNoticeResultServer();
                $Notice->updateParcelNotice($v['f_parcel_id'], ['f_weixin_num' => ['exp', 'f_weixin_num+1']], $v['table_name']);

                $n_data['f_parcel_id'] = $v['f_parcel_id'];
                $n_data['f_weixin_send_time'] = date('YmdHis');
                $n_data['f_weixin_send_time_stamp'] = time();
                if ($arr_weixin['status'] == 1) {
                    $n_data['f_weixin_notice'] = 2; //失败
                } else {
                    $n_data['f_weixin_notice'] = 3; //已发送
                }

                $Notice->updateParcelNotice($v['f_parcel_id'], $n_data, $v['table_name']);

            }
            $this->output(true ,array(),'微信发送成功');

        } // 变更包裹状态 =》 短信
        elseif ($data['resendType'] == 2)
        {
            $packetList = $parcelService->getAllRetentionStorage($data['stationId'], $data['packetType'], $time['startTime'], $time['endTime'], $data['noticeWay'] ,$mobile ,$mailNO);


            if ($packetList != false) {

                $speed = $list = [];

                foreach ($packetList as $v) {

                    if ($v['f_take_code'] == 0) {
                        $speed[] = $v['f_parcel_id'];
                    } else {
                        $list[] = $v['f_parcel_id'];
                    }

                }

                //普通版包裹发送通知
                $result['CVN'] = count($list) ;
                $result['SVN'] = count($speed) ;

                //监控通知
                if (count($list) > C('TASK_WARNING') || count($speed) > C('TASK_WARNING')) {
                    $con = C('AUTOGRAPH') . "短信通知任务数量过大，请注意处理：CVN:" . count($list) . ',SVN:' . count($speed);
                    send_sms(C('NOTICE_MOBILE'), $con);
                }

                $common = new \Home\Controller\CommonController();
                $common->queueSendSms($list ,1);

                //极速版通知
                $SpeedServer = new SpeedController();

                $SpeedServer->speedSendSms($speed ,1);

                $this -> output(true , array() ,'短信发送成功');
            }

        }
    }


    /**
     * 获取滞留时间段
     * @param $retention 滞留时间：0 全部；123 今日；1 一天；2 两天；3 三天及以上；
     * @return array    查询开始和结束时间
     */
    public function getRetentionTime($retention){

        $time = array();
        $retention = (int)$retention;

        if ($retention == 123)
        {
            $time['startTime'] = $time['endTime'] = date('Y-m-d');
        }elseif ($retention == 3)
        {
            $time['startTime'] = date('Y-m-01', strtotime("-1 month"));
            $time['endTime'] = date('Y-m-d',strtotime('-3 day'));
        }
        elseif( $retention < 3 && $retention > 0)
        {
            $time['startTime'] = $time['endTime'] = date('Y-m-d',strtotime('-'.$retention.' day'));
        }
        else
        {
            $time['startTime'] = date('Y-m-01', strtotime("-1 month"));
            $time['endTime'] = date('Y-m-d');
        }

        return $time;
    }
    /**
     * @desc:  查询多状态包裹(根据不同的快递公司)
     * @Author: xushu
     * @update: 17/07/03
     * */
    public function queryPacketListByCompany()
    {
        $data = I('param.');

        if (empty($data['stationId']) || $data['packetType'] == '' || empty($data['companyID'])) {
            $this->param_error();
        }

        //时间筛选为空、通知中和通知失败的时候默认搜索两个月的数据
        //防止出现每月一号数据异常
        if (empty($data['beginDate']) || $data['packetType'] == 2 || $data['packetType'] == 5) {

            $startTime = date('Y-m-01', strtotime("-1 month"));
            $endTime = date('Y-m-d');
        }

        $parcelService = new \Home\Server\ParcelService();
        //总数量
        $count = $parcelService->countConditionStorage($data['stationId'], '', $data['beginDate'], $data['packetType'], $data['companyID'], '', '', $startTime, $endTime);

        //查询通知中和通知失败的数据
        //通知中、通知失败结果不受条件限制
        $noticeIng = $parcelService->countConditionStorage($data['stationId'], 0, '', 2, $data['companyID'], '', '', date('Y-m-01', strtotime("-1 month")), date('Y-m-d'));

        $noticeFail = $parcelService->countConditionStorage($data['stationId'], 0, '', 5, $data['companyID'], '', '', date('Y-m-01', strtotime("-1 month")), date('Y-m-d'));



        $page = !empty($data['currentPage']) ? $data['currentPage'] : 1;

        //兼容错误的APP参数
        if (strpos($data['currentPage'], 'Optional') !== False) {
            $page = substr($data['currentPage'], 9, -1);
        }

        $pageSize =  20;
        $totalPages = ceil($count / $pageSize);

        //查询数据
        $packetList = $parcelService->getConditionStorage($data['stationId'], '', $data['beginDate'], $data['packetType'], $page, $pageSize, $data['companyID'], '', '', $startTime, $endTime);

        $noticeIng == false ? $noticeIng = '0' : $noticeIng;
        $noticeFail == false ? $noticeFail = '0' : $noticeFail;

        $result = array(
            'count' => $count,
            'noticeIng' => $noticeIng,
            'noticeFail' => $noticeFail,
            'pcketinfo' => $packetList,
            'totlePage' => $totalPages
        );

        $this->output(true, $result);

    }

    /**
     * @desc:   根据拼音获取快递公司名称
     * @Author: zhoutai
     * @update: 16/11/24
     * */
    public function queryCompanyInfoByPinYin() {
        $data = I('param.');
        if (empty($data['pinYin']))
            $this->output(0);
        $companyData = D('tp_express_company')->where(array('f_company_pinyin' => $data['pinYin']))->field('
            f_company_id as companyId,
            f_company_name as companyName
        ')->find();
        if (empty($companyData))
            $this->output(0);
        $this->output(1, $companyData);
    }

    /**
     * @desc:  获取快递公司列 表
     * @Author: zhoutai
     * @update: 16/11/25
     * */
    public function queryDeliveryCompany($getData = 0) {
        $data = D('tp_express_company')->field('
            f_company_pinyin as fCompanyPinyin,
            f_company_id as fCompanyId,
            f_company_id as fCompanyCode,
            f_company_name as fCompanyName,
            f_company_status as fCompanyStatus,
            f_company_sort as fCompanySort,
            f_company_create_time as fCompanyCreateTime,
            f_group_pinyin,
            f_company_initials AS fCompanyInitials
        ')
            ->order('`f_company_sort` ASC')
            ->select();

        if ($getData == 2) {
            return $data;
        }
        !empty($data) || $this->output(0);
        $this->output(1, $data);
    }

    /**
     * Function queryDeliveryCompanyGroup
     *
     * Author: 黄盖
     * Date: 2017-3-13 10:07
     * Info: 快递公司首字母分组
     */
    public function queryDeliveryCompanyGroup() {
        $DeliveryData = $this->queryDeliveryCompany(2);

        //热门数据
        $HotData = Array();


        $GroupData = $OUTData = Array();

        foreach ($DeliveryData as $Key => $Val) {
            $GroupData[strtoupper(substr($Val['f_group_pinyin'], 0, 1))][] = $Val;

            //如果排序小于300，则热门
            if ($Val['fCompanySort'] < 300) {
                $HotData[] = $Val;
            }
        }

        ksort($GroupData);

        //将热门数据插入开头
        $OUTData[] = Array('groupName' => '#', 'Companys' => $HotData);

        //处理成APP想要的数据
        foreach ($GroupData as $GKey => $GVal) {
            $OUTData[] = Array('groupName' => $GKey, 'Companys' => $GVal);
        }

        $this->output(1, $OUTData);
    }

    /**
     * @desc:  获取快递公司列 表
     * @Author: zhoutai
     * @update: 16/11/25
     * */
    public function queryDeliveryCompany_bak($getData = 0) {
        if ($getData == 0){
            $data = '{
                        "a": 0,
                        "m": "请求成功",
                        "success": true,
                        "e": "0",
                        "d": [
                            {
                                "fCompanyPinyin": "zhongtong",
                                "fCompanyId": "125",
                                "fCompanyCode": "125",
                                "fCompanyName": "中通速递",
                                "fCompanyStatus": "0",
                                "fCompanySort": "100",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "zhongtongsudi",
                                "fCompanyInitials": "ZTO"
                            },
                            {
                                "fCompanyPinyin": "yunda",
                                "fCompanyId": "109",
                                "fCompanyCode": "109",
                                "fCompanyName": "韵达快运",
                                "fCompanyStatus": "0",
                                "fCompanySort": "103",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "yundakuaiyun",
                                "fCompanyInitials": "YD"
                            },
                            {
                                "fCompanyPinyin": "yuantong",
                                "fCompanyId": "108",
                                "fCompanyCode": "108",
                                "fCompanyName": "圆通速递",
                                "fCompanyStatus": "0",
                                "fCompanySort": "105",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "yuantongsudi",
                                "fCompanyInitials": "YTO"
                            },
                            {
                                "fCompanyPinyin": "huitongkuaidi",
                                "fCompanyId": "5",
                                "fCompanyCode": "5",
                                "fCompanyName": "百世快递",
                                "fCompanyStatus": "0",
                                "fCompanySort": "115",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "baishikuaidi",
                                "fCompanyInitials": "BS"
                            },
                            {
                                "fCompanyPinyin": "ems",
                                "fCompanyId": "23",
                                "fCompanyCode": "23",
                                "fCompanyName": "EMS",
                                "fCompanyStatus": "0",
                                "fCompanySort": "120",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "ems",
                                "fCompanyInitials": "EMS"
                            },
                            {
                                "fCompanyPinyin": "tiantian",
                                "fCompanyId": "92",
                                "fCompanyCode": "92",
                                "fCompanyName": "天天快递",
                                "fCompanyStatus": "0",
                                "fCompanySort": "130",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "tiantiankuaidi",
                                "fCompanyInitials": "TT"
                            },
                            {
                                "fCompanyPinyin": "annengwuliu",
                                "fCompanyId": "184",
                                "fCompanyCode": "184",
                                "fCompanyName": "安能物流",
                                "fCompanyStatus": "0",
                                "fCompanySort": "140",
                                "fCompanyCreateTime": "201611011430",
                                "f_group_pinyin": "annengwuliu",
                                "fCompanyInitials": "AN"
                            },
                            {
                                "fCompanyPinyin": "GTKD",
                                "fCompanyId": "183",
                                "fCompanyCode": "183",
                                "fCompanyName": "国通快递",
                                "fCompanyStatus": "0",
                                "fCompanySort": "180",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "guotongkuaidi",
                                "fCompanyInitials": "GT"
                            },
                            {
                                "fCompanyPinyin": "youzhengguonei",
                                "fCompanyId": "181",
                                "fCompanyCode": "181",
                                "fCompanyName": "中国邮政/平邮",
                                "fCompanyStatus": "0",
                                "fCompanySort": "191",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "zhongguoyouzheng",
                                "fCompanyInitials": "YZ"
                            },
                            {
                                "fCompanyPinyin": "shunfeng",
                                "fCompanyId": "77",
                                "fCompanyCode": "77",
                                "fCompanyName": "顺丰速运",
                                "fCompanyStatus": "0",
                                "fCompanySort": "192",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "shunfengsuyun",
                                "fCompanyInitials": "SF"
                            },
                            {
                                "fCompanyPinyin": "shentong",
                                "fCompanyId": "133",
                                "fCompanyCode": "133",
                                "fCompanyName": "申通快递",
                                "fCompanyStatus": "0",
                                "fCompanySort": "200",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "shentongkuaidi",
                                "fCompanyInitials": "STO"
                            },
                            {
                                "fCompanyPinyin": "quanfengkuaidi",
                                "fCompanyId": "73",
                                "fCompanyCode": "73",
                                "fCompanyName": "全峰快递",
                                "fCompanyStatus": "0",
                                "fCompanySort": "600",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "quanfengkuaidi",
                                "fCompanyInitials": "QF"
                            },
                            {
                                "fCompanyPinyin": "huitongkuaidi_2",
                                "fCompanyId": "34",
                                "fCompanyCode": "34",
                                "fCompanyName": "汇通快运",
                                "fCompanyStatus": "0",
                                "fCompanySort": "700",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "huitongkuaiyun",
                                "fCompanyInitials": "HT"
                            },
                            {
                                "fCompanyPinyin": "zhaijisong",
                                "fCompanyId": "126",
                                "fCompanyCode": "126",
                                "fCompanyName": "宅急送",
                                "fCompanyStatus": "0",
                                "fCompanySort": "800",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "zhaijisong",
                                "fCompanyInitials": "ZJS"
                            },
                            {
                                "fCompanyPinyin": "rufengda",
                                "fCompanyId": "26",
                                "fCompanyCode": "26",
                                "fCompanyName": "凡客如风达",
                                "fCompanyStatus": "0",
                                "fCompanySort": "930",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "fankerufengda",
                                "fCompanyInitials": "FKR"
                            },
                            {
                                "fCompanyPinyin": "debangwuliu",
                                "fCompanyId": "182",
                                "fCompanyCode": "182",
                                "fCompanyName": "德邦物流",
                                "fCompanyStatus": "0",
                                "fCompanySort": "950",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "debangwuliu",
                                "fCompanyInitials": "DB"
                            },
                            {
                                "fCompanyPinyin": "weipinhui",
                                "fCompanyId": "180",
                                "fCompanyCode": "180",
                                "fCompanyName": "唯品会",
                                "fCompanyStatus": "0",
                                "fCompanySort": "960",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "weipinhui",
                                "fCompanyInitials": "WPH"
                            },
                            {
                                "fCompanyPinyin": "suningyigou",
                                "fCompanyId": "179",
                                "fCompanyCode": "179",
                                "fCompanyName": "苏宁易购",
                                "fCompanyStatus": "0",
                                "fCompanySort": "970",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "suningyigou",
                                "fCompanyInitials": "SN"
                            },
                            {
                                "fCompanyPinyin": "rufengda",
                                "fCompanyId": "177",
                                "fCompanyCode": "177",
                                "fCompanyName": "如风达",
                                "fCompanyStatus": "0",
                                "fCompanySort": "985",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "rufengda",
                                "fCompanyInitials": "RFD"
                            },
                            {
                                "fCompanyPinyin": "jd",
                                "fCompanyId": "178",
                                "fCompanyCode": "178",
                                "fCompanyName": "京东商城",
                                "fCompanyStatus": "0",
                                "fCompanySort": "993",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "jingdongshangc",
                                "fCompanyInitials": "JD"
                            },
                            {
                                "fCompanyPinyin": "nanjingshengbang",
                                "fCompanyId": "176",
                                "fCompanyCode": "176",
                                "fCompanyName": "晟邦物流",
                                "fCompanyStatus": "0",
                                "fCompanySort": "994",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "shengbangwuliu",
                                "fCompanyInitials": "SB"
                            },
                            {
                                "fCompanyPinyin": "suer",
                                "fCompanyId": "81",
                                "fCompanyCode": "81",
                                "fCompanyName": "速尔物流",
                                "fCompanyStatus": "0",
                                "fCompanySort": "995",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "suerwuliu",
                                "fCompanyInitials": "SE"
                            },
                            {
                                "fCompanyPinyin": "youshuwuliu",
                                "fCompanyId": "115",
                                "fCompanyCode": "115",
                                "fCompanyName": "优速物流",
                                "fCompanyStatus": "0",
                                "fCompanySort": "996",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "youshuwuliu",
                                "fCompanyInitials": "YS"
                            },
                            {
                                "fCompanyPinyin": "kuaijiesudi",
                                "fCompanyId": "53",
                                "fCompanyCode": "53",
                                "fCompanyName": "快捷速递",
                                "fCompanyStatus": "0",
                                "fCompanySort": "998",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "kuaijiesudi",
                                "fCompanyInitials": "KJ"
                            },
                            {
                                "fCompanyPinyin": "quanyikuaidi",
                                "fCompanyId": "72",
                                "fCompanyCode": "72",
                                "fCompanyName": "全一快递",
                                "fCompanyStatus": "0",
                                "fCompanySort": "999",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "quanyikuaidi",
                                "fCompanyInitials": "QY"
                            },
                            {
                                "fCompanyPinyin": "rufengda",
                                "fCompanyId": "75",
                                "fCompanyCode": "75",
                                "fCompanyName": "如风达快递",
                                "fCompanyStatus": "0",
                                "fCompanySort": "1000",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "rufengdakuaidi",
                                "fCompanyInitials": "RFD"
                            },
                            {
                                "fCompanyPinyin": "tianmaochaoshi",
                                "fCompanyId": "188",
                                "fCompanyCode": "188",
                                "fCompanyName": "天猫超市",
                                "fCompanyStatus": "0",
                                "fCompanySort": "1000",
                                "fCompanyCreateTime": "201704011015",
                                "f_group_pinyin": "tianmaochaoshi",
                                "fCompanyInitials": "TM"
                            },
                            {
                                "fCompanyPinyin": "wxwl",
                                "fCompanyId": "185",
                                "fCompanyCode": "185",
                                "fCompanyName": "万象物流",
                                "fCompanyStatus": "0",
                                "fCompanySort": "1002",
                                "fCompanyCreateTime": "201701031751",
                                "f_group_pinyin": "wanxiangwuliu",
                                "fCompanyInitials": "WX"
                            },
                            {
                                "fCompanyPinyin": "saiaodi",
                                "fCompanyId": "186",
                                "fCompanyCode": "186",
                                "fCompanyName": "赛澳递",
                                "fCompanyStatus": "0",
                                "fCompanySort": "1003",
                                "fCompanyCreateTime": "201701031751",
                                "f_group_pinyin": "saiaodi",
                                "fCompanyInitials": "SAD"
                            },
                            {
                                "fCompanyPinyin": "menduimen",
                                "fCompanyId": "187",
                                "fCompanyCode": "187",
                                "fCompanyName": "门对门",
                                "fCompanyStatus": "0",
                                "fCompanySort": "1004",
                                "fCompanyCreateTime": "201701031751",
                                "f_group_pinyin": "menduimen",
                                "fCompanyInitials": "MDM"
                            },
                            {
                                "fCompanyPinyin": "qita",
                                "fCompanyId": "134",
                                "fCompanyCode": "134",
                                "fCompanyName": "其他",
                                "fCompanyStatus": "0",
                                "fCompanySort": "2001",
                                "fCompanyCreateTime": "201606211751",
                                "f_group_pinyin": "qita",
                                "fCompanyInitials": "OT"
                            }
                        ]
                    }';
        }else if ($getData == 2){

            $data = D('tp_express_company')->field('
            f_company_pinyin as fCompanyPinyin,
            f_company_id as fCompanyId,
            f_company_id as fCompanyCode,
            f_company_name as fCompanyName,
            f_company_status as fCompanyStatus,
            f_company_sort as fCompanySort,
            f_company_create_time as fCompanyCreateTime,
            f_group_pinyin,
            f_company_initials AS fCompanyInitials
        ')
                ->order('`f_company_sort` ASC')
                ->select();

        }


        if ($getData == 2) {
            return $data;
        }
//        dump($data);
        !empty($data) || $this->output(0);
//        $this->output(1, $data);
        echo  $data;

    }

    /**
     * Function queryDeliveryCompanyGroup
     *
     * Author: 黄盖
     * Date: 2017-3-13 10:07
     * Info: 快递公司首字母分组
     */
    public function queryDeliveryCompanyGroup_bak() {
        /*
        $DeliveryData = $this->queryDeliveryCompany(2);

        //热门数据
        $HotData = Array();


        $GroupData = $OUTData = Array();

        foreach ($DeliveryData as $Key => $Val) {
            $GroupData[strtoupper(substr($Val['f_group_pinyin'], 0, 1))][] = $Val;

            //如果排序小于300，则热门
            if ($Val['fCompanySort'] < 300) {
                $HotData[] = $Val;
            }
        }

        ksort($GroupData);

        //将热门数据插入开头
        $OUTData[] = Array('groupName' => '#', 'Companys' => $HotData);

        //处理成APP想要的数据
        foreach ($GroupData as $GKey => $GVal) {
            $OUTData[] = Array('groupName' => $GKey, 'Companys' => $GVal);
        }

        $this->output(1, $OUTData);
        */
        $data='
        {
    "a": 0,
    "m": "请求成功1",
    "success": true,
    "e": "0",
    "d": [
        {
            "groupName": "#",
            "Companys": [
                {
                    "fCompanyPinyin": "zhongtong",
                    "fCompanyId": "125",
                    "fCompanyCode": "125",
                    "fCompanyName": "中通速递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "100",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "zhongtongsudi",
                    "fCompanyInitials": "ZTO"
                },
                {
                    "fCompanyPinyin": "yunda",
                    "fCompanyId": "109",
                    "fCompanyCode": "109",
                    "fCompanyName": "韵达快运",
                    "fCompanyStatus": "0",
                    "fCompanySort": "103",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "yundakuaiyun",
                    "fCompanyInitials": "YD"
                },
                {
                    "fCompanyPinyin": "yuantong",
                    "fCompanyId": "108",
                    "fCompanyCode": "108",
                    "fCompanyName": "圆通速递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "105",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "yuantongsudi",
                    "fCompanyInitials": "YTO"
                },
                {
                    "fCompanyPinyin": "huitongkuaidi",
                    "fCompanyId": "5",
                    "fCompanyCode": "5",
                    "fCompanyName": "百世快递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "115",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "baishikuaidi",
                    "fCompanyInitials": "BS"
                },
                {
                    "fCompanyPinyin": "ems",
                    "fCompanyId": "23",
                    "fCompanyCode": "23",
                    "fCompanyName": "EMS",
                    "fCompanyStatus": "0",
                    "fCompanySort": "120",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "ems",
                    "fCompanyInitials": "EMS"
                },
                {
                    "fCompanyPinyin": "tiantian",
                    "fCompanyId": "92",
                    "fCompanyCode": "92",
                    "fCompanyName": "天天快递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "130",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "tiantiankuaidi",
                    "fCompanyInitials": "TT"
                },
                {
                    "fCompanyPinyin": "annengwuliu",
                    "fCompanyId": "184",
                    "fCompanyCode": "184",
                    "fCompanyName": "安能物流",
                    "fCompanyStatus": "0",
                    "fCompanySort": "140",
                    "fCompanyCreateTime": "201611011430",
                    "f_group_pinyin": "annengwuliu",
                    "fCompanyInitials": "AN"
                },
                {
                    "fCompanyPinyin": "GTKD",
                    "fCompanyId": "183",
                    "fCompanyCode": "183",
                    "fCompanyName": "国通快递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "180",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "guotongkuaidi",
                    "fCompanyInitials": "GT"
                },
                {
                    "fCompanyPinyin": "youzhengguonei",
                    "fCompanyId": "181",
                    "fCompanyCode": "181",
                    "fCompanyName": "中国邮政/平邮",
                    "fCompanyStatus": "0",
                    "fCompanySort": "191",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "zhongguoyouzheng",
                    "fCompanyInitials": "YZ"
                },
                {
                    "fCompanyPinyin": "shunfeng",
                    "fCompanyId": "77",
                    "fCompanyCode": "77",
                    "fCompanyName": "顺丰速运",
                    "fCompanyStatus": "0",
                    "fCompanySort": "192",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "shunfengsuyun",
                    "fCompanyInitials": "SF"
                },
                {
                    "fCompanyPinyin": "shentong",
                    "fCompanyId": "133",
                    "fCompanyCode": "133",
                    "fCompanyName": "申通快递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "200",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "shentongkuaidi",
                    "fCompanyInitials": "STO"
                }
            ]
        },
        {
            "groupName": "A",
            "Companys": [
                {
                    "fCompanyPinyin": "annengwuliu",
                    "fCompanyId": "184",
                    "fCompanyCode": "184",
                    "fCompanyName": "安能物流",
                    "fCompanyStatus": "0",
                    "fCompanySort": "140",
                    "fCompanyCreateTime": "201611011430",
                    "f_group_pinyin": "annengwuliu",
                    "fCompanyInitials": "AN"
                }
            ]
        },
        {
            "groupName": "B",
            "Companys": [
                {
                    "fCompanyPinyin": "huitongkuaidi",
                    "fCompanyId": "5",
                    "fCompanyCode": "5",
                    "fCompanyName": "百世快递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "115",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "baishikuaidi",
                    "fCompanyInitials": "BS"
                }
            ]
        },
        {
            "groupName": "D",
            "Companys": [
                {
                    "fCompanyPinyin": "debangwuliu",
                    "fCompanyId": "182",
                    "fCompanyCode": "182",
                    "fCompanyName": "德邦物流",
                    "fCompanyStatus": "0",
                    "fCompanySort": "950",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "debangwuliu",
                    "fCompanyInitials": "DB"
                }
            ]
        },
        {
            "groupName": "E",
            "Companys": [
                {
                    "fCompanyPinyin": "ems",
                    "fCompanyId": "23",
                    "fCompanyCode": "23",
                    "fCompanyName": "EMS",
                    "fCompanyStatus": "0",
                    "fCompanySort": "120",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "ems",
                    "fCompanyInitials": "EMS"
                }
            ]
        },
        {
            "groupName": "F",
            "Companys": [
                {
                    "fCompanyPinyin": "rufengda",
                    "fCompanyId": "26",
                    "fCompanyCode": "26",
                    "fCompanyName": "凡客如风达",
                    "fCompanyStatus": "0",
                    "fCompanySort": "930",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "fankerufengda",
                    "fCompanyInitials": "FKR"
                }
            ]
        },
        {
            "groupName": "G",
            "Companys": [
                {
                    "fCompanyPinyin": "GTKD",
                    "fCompanyId": "183",
                    "fCompanyCode": "183",
                    "fCompanyName": "国通快递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "180",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "guotongkuaidi",
                    "fCompanyInitials": "GT"
                }
            ]
        },
        {
            "groupName": "H",
            "Companys": [
                {
                    "fCompanyPinyin": "huitongkuaidi_2",
                    "fCompanyId": "34",
                    "fCompanyCode": "34",
                    "fCompanyName": "汇通快运",
                    "fCompanyStatus": "0",
                    "fCompanySort": "700",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "huitongkuaiyun",
                    "fCompanyInitials": "HT"
                }
            ]
        },
        {
            "groupName": "J",
            "Companys": [
                {
                    "fCompanyPinyin": "jd",
                    "fCompanyId": "178",
                    "fCompanyCode": "178",
                    "fCompanyName": "京东商城",
                    "fCompanyStatus": "0",
                    "fCompanySort": "993",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "jingdongshangc",
                    "fCompanyInitials": "JD"
                }
            ]
        },
        {
            "groupName": "K",
            "Companys": [
                {
                    "fCompanyPinyin": "kuaijiesudi",
                    "fCompanyId": "53",
                    "fCompanyCode": "53",
                    "fCompanyName": "快捷速递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "998",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "kuaijiesudi",
                    "fCompanyInitials": "KJ"
                }
            ]
        },
        {
            "groupName": "M",
            "Companys": [
                {
                    "fCompanyPinyin": "menduimen",
                    "fCompanyId": "187",
                    "fCompanyCode": "187",
                    "fCompanyName": "门对门",
                    "fCompanyStatus": "0",
                    "fCompanySort": "1004",
                    "fCompanyCreateTime": "201701031751",
                    "f_group_pinyin": "menduimen",
                    "fCompanyInitials": "MDM"
                }
            ]
        },
        {
            "groupName": "Q",
            "Companys": [
                {
                    "fCompanyPinyin": "quanfengkuaidi",
                    "fCompanyId": "73",
                    "fCompanyCode": "73",
                    "fCompanyName": "全峰快递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "600",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "quanfengkuaidi",
                    "fCompanyInitials": "QF"
                },
                {
                    "fCompanyPinyin": "quanyikuaidi",
                    "fCompanyId": "72",
                    "fCompanyCode": "72",
                    "fCompanyName": "全一快递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "999",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "quanyikuaidi",
                    "fCompanyInitials": "QY"
                },
                {
                    "fCompanyPinyin": "qita",
                    "fCompanyId": "134",
                    "fCompanyCode": "134",
                    "fCompanyName": "其他",
                    "fCompanyStatus": "0",
                    "fCompanySort": "2001",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "qita",
                    "fCompanyInitials": "OT"
                }
            ]
        },
        {
            "groupName": "R",
            "Companys": [
                {
                    "fCompanyPinyin": "rufengda",
                    "fCompanyId": "177",
                    "fCompanyCode": "177",
                    "fCompanyName": "如风达",
                    "fCompanyStatus": "0",
                    "fCompanySort": "985",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "rufengda",
                    "fCompanyInitials": "RFD"
                },
                {
                    "fCompanyPinyin": "rufengda",
                    "fCompanyId": "75",
                    "fCompanyCode": "75",
                    "fCompanyName": "如风达快递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "1000",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "rufengdakuaidi",
                    "fCompanyInitials": "RFD"
                }
            ]
        },
        {
            "groupName": "S",
            "Companys": [
                {
                    "fCompanyPinyin": "shunfeng",
                    "fCompanyId": "77",
                    "fCompanyCode": "77",
                    "fCompanyName": "顺丰速运",
                    "fCompanyStatus": "0",
                    "fCompanySort": "192",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "shunfengsuyun",
                    "fCompanyInitials": "SF"
                },
                {
                    "fCompanyPinyin": "shentong",
                    "fCompanyId": "133",
                    "fCompanyCode": "133",
                    "fCompanyName": "申通快递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "200",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "shentongkuaidi",
                    "fCompanyInitials": "STO"
                },
                {
                    "fCompanyPinyin": "suningyigou",
                    "fCompanyId": "179",
                    "fCompanyCode": "179",
                    "fCompanyName": "苏宁易购",
                    "fCompanyStatus": "0",
                    "fCompanySort": "970",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "suningyigou",
                    "fCompanyInitials": "SN"
                },
                {
                    "fCompanyPinyin": "nanjingshengbang",
                    "fCompanyId": "176",
                    "fCompanyCode": "176",
                    "fCompanyName": "晟邦物流",
                    "fCompanyStatus": "0",
                    "fCompanySort": "994",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "shengbangwuliu",
                    "fCompanyInitials": "SB"
                },
                {
                    "fCompanyPinyin": "suer",
                    "fCompanyId": "81",
                    "fCompanyCode": "81",
                    "fCompanyName": "速尔物流",
                    "fCompanyStatus": "0",
                    "fCompanySort": "995",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "suerwuliu",
                    "fCompanyInitials": "SE"
                },
                {
                    "fCompanyPinyin": "saiaodi",
                    "fCompanyId": "186",
                    "fCompanyCode": "186",
                    "fCompanyName": "赛澳递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "1003",
                    "fCompanyCreateTime": "201701031751",
                    "f_group_pinyin": "saiaodi",
                    "fCompanyInitials": "SAD"
                }
            ]
        },
        {
            "groupName": "T",
            "Companys": [
                {
                    "fCompanyPinyin": "tiantian",
                    "fCompanyId": "92",
                    "fCompanyCode": "92",
                    "fCompanyName": "天天快递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "130",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "tiantiankuaidi",
                    "fCompanyInitials": "TT"
                },
                {
                    "fCompanyPinyin": "tianmaochaoshi",
                    "fCompanyId": "188",
                    "fCompanyCode": "188",
                    "fCompanyName": "天猫超市",
                    "fCompanyStatus": "0",
                    "fCompanySort": "1000",
                    "fCompanyCreateTime": "201704011015",
                    "f_group_pinyin": "tianmaochaoshi",
                    "fCompanyInitials": "TM"
                }
            ]
        },
        {
            "groupName": "W",
            "Companys": [
                {
                    "fCompanyPinyin": "weipinhui",
                    "fCompanyId": "180",
                    "fCompanyCode": "180",
                    "fCompanyName": "唯品会",
                    "fCompanyStatus": "0",
                    "fCompanySort": "960",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "weipinhui",
                    "fCompanyInitials": "WPH"
                },
                {
                    "fCompanyPinyin": "wxwl",
                    "fCompanyId": "185",
                    "fCompanyCode": "185",
                    "fCompanyName": "万象物流",
                    "fCompanyStatus": "0",
                    "fCompanySort": "1002",
                    "fCompanyCreateTime": "201701031751",
                    "f_group_pinyin": "wanxiangwuliu",
                    "fCompanyInitials": "WX"
                }
            ]
        },
        {
            "groupName": "Y",
            "Companys": [
                {
                    "fCompanyPinyin": "yunda",
                    "fCompanyId": "109",
                    "fCompanyCode": "109",
                    "fCompanyName": "韵达快运",
                    "fCompanyStatus": "0",
                    "fCompanySort": "103",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "yundakuaiyun",
                    "fCompanyInitials": "YD"
                },
                {
                    "fCompanyPinyin": "yuantong",
                    "fCompanyId": "108",
                    "fCompanyCode": "108",
                    "fCompanyName": "圆通速递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "105",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "yuantongsudi",
                    "fCompanyInitials": "YTO"
                },
                {
                    "fCompanyPinyin": "youshuwuliu",
                    "fCompanyId": "115",
                    "fCompanyCode": "115",
                    "fCompanyName": "优速物流",
                    "fCompanyStatus": "0",
                    "fCompanySort": "996",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "youshuwuliu",
                    "fCompanyInitials": "YS"
                }
            ]
        },
        {
            "groupName": "Z",
            "Companys": [
                {
                    "fCompanyPinyin": "zhongtong",
                    "fCompanyId": "125",
                    "fCompanyCode": "125",
                    "fCompanyName": "中通速递",
                    "fCompanyStatus": "0",
                    "fCompanySort": "100",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "zhongtongsudi",
                    "fCompanyInitials": "ZTO"
                },
                {
                    "fCompanyPinyin": "youzhengguonei",
                    "fCompanyId": "181",
                    "fCompanyCode": "181",
                    "fCompanyName": "中国邮政/平邮",
                    "fCompanyStatus": "0",
                    "fCompanySort": "191",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "zhongguoyouzheng",
                    "fCompanyInitials": "YZ"
                },
                {
                    "fCompanyPinyin": "zhaijisong",
                    "fCompanyId": "126",
                    "fCompanyCode": "126",
                    "fCompanyName": "宅急送",
                    "fCompanyStatus": "0",
                    "fCompanySort": "800",
                    "fCompanyCreateTime": "201606211751",
                    "f_group_pinyin": "zhaijisong",
                    "fCompanyInitials": "ZJS"
                }
            ]
        }
    ]
}';

        echo $data;
    }

    /**
     * 获取价格接口（根据产品类型和站点是否有代理商）
     * @again quyang 2017-1-20
     * @author cheng
     */
    public function getPrice($tag = '') {
        $data = I('param.');
        if (empty($data['productId']) || empty($data['stationId'])) {
            $this->param_error();
        }
        //根据产品类型不同获取价格
        $info = D('Home/Product')->field('F_CREATE_USER,F_PRODUCT_PRICE,f_product_type_id')->where(array('F_PRODUCT_ID' => $data['productId']))->find();
        if ($info['f_product_type_id'] == 2) {
            //根据stationId获取代理商id
            $sp_data = D('Home/User')->where(array('f_user_id' => $data['stationId']))->find();
            if ($sp_data) { //有代理商获取代理商价格
                $result['price'] = D('Home/Product')->where(array('F_CREATE_USER' => $sp_data['f_proxy_id']))->getField('F_PRODUCT_PRICE');
            } else {
                $result['price'] = $info['F_PRODUCT_PRICE'];
            }
            if ($tag) {
                return $result['price'];
            } else {
                $this->output($status = 1, $result);
            }
        } else {
            $result['price'] = $info['F_PRODUCT_PRICE'];
            if ($tag) {
                return $result['price'];
            } else {
                $this->output($status = 1, $result);
            }
        }
    }

    /**
     * 自动生成订单接口
     * @author cheng
     */
    public function generateOrder() {
        $data = I('param.');
        if (empty($data['productId']) || empty($data['count']) || empty($data['userId']) || empty($data['stationId'])) {
            $this->param_error();
        }

        //限制只有第一次可以购买试用套餐
        if ($data['productId'] == '3') {
            $Order = new \Home\Model\OrderProductModel();
            if ($Order->queryProductStatus($data['userId']) > 0) {
                $this->auto_error('已经支付成功，请返回登录');
            }
        }

        //查询商品表获取商品信息
        $p_data = D('Home/Product')->getProductInfo($data['productId']);
        empty($p_data) && $this->output(0);
        //插入数据到订单表
        $d_price = $this->getPrice($tag = true);
        $o_data = array(
            'F_ORDER_ID' => get_Ordernums(),
            'F_AMOUNT' => $data['count'] * $d_price,
            'F_USER_ID' => $data['userId'],
            'F_CREATE_TIME' => date('YmdHis'),
            'F_STATE' => '001',
            'F_HANDLE_TIME' => date('YmdHis'),
        );
        $o_result = D('Home/Order')->saveOrder($o_data);
        //插入数据到订单商品表
        if ($o_result) {
            $op_data = array(
                'F_ORDER_PRODUCT_ID' => get_Ordernums(),
                'F_ORDER_ID' => $o_data['F_ORDER_ID'],
                'F_PRODUCT_ID' => $p_data['F_PRODUCT_ID'],
                'F_TYPE' => 0,
                //'F_SKU_ID' => ,
                'F_COUNT' => $data['count'],
                'F_SINGLE_PRICE' => $p_data['F_PRODUCT_PRICE'],
                'F_AMOUNT' => $data['count'] * $d_price,
                'F_PRODUCT_NAME' => $p_data['F_PRODUCT_NAME'],
                'f_create_time' => date('YmdHis'),
                    //'F_USER_ID' => ,
            );
            $op_result = D('Home/OrderProduct')->saveOrderProduct($op_data);
            //插入数据到订单收件人地址信息表
            $oa_data = array(
                'F_ORDER_ID' => $o_data['F_ORDER_ID']
                    //'F_RECIEVE_NAME' =>
                    //'F_mobile' =>
                    //'f_address' =>
            );
            $oa_result = D('Home/OrderAddress')->saveOrderAddress($oa_data);
        }
        //关联查询订单表、订单商品表和订单收件人地址表
        $result = D('Home/Order')->getOrderProductAddress($o_data['F_ORDER_ID']);
        if ($result) {
            $this->output($status = 1, $result);
        } else {
            $this->output(0);
        }
    }

    /**
     * @desc: 快递公司数量统计接口
     * @Author: delayhsiao
     * @again quyang 2017-1-20
     * @update: 2016-11-26
     * */
    public function countCompanyPacket() {
        $data = I('param.');
        if (empty($data['stationId']) || $data['state'] == '') {
            $this->param_error();
        }
        $parcelDetail = new \Home\Server\QueryParcelService();
        $countList = $parcelDetail->countCompanyPacket($data);
        $this->output(true, $countList);
    }

    /**
     * @desc: 接收微信通知状态回调
     * @Author: delayhsiao
     * @again quyang 2017-1-21
     * @update: 2016-11-29
     * */
    public function setPackageNoticed() {
        $data = I('param.');
        if (empty($data['mailno']) || empty($data['mobile']) || $data['takecode'] == '') {
            $this->param_error();
        }

        //微信回调type  普通版为0  专业版入库为1  极速版入库为2
        if ($data['type'] == '2') {

            //分隔获取包裹id
            $parcelId = explode('(', $data['mailno']);

            $Notice = new \Home\Server\ParcelNoticeResultServer();

            $notice = array(
                'f_weixin_notice' => 1,
                'f_weixin_success_time' => date('YmdHis'),
                'f_weixin_success_time_stamp' => time()
            );

            $result = $Notice->updateParcelNotice($parcelId[0], $notice);

            if ($result) {
                $this->output(true);
            }
        } else {
            $parcelDetail = new \Home\Server\QueryParcelService();
            $where = " `f_mail_no`= '{$data['mailno']}' and `f_recipient_mobile` = '{$data['mobile']}' "; //and `f_take_code` = {$data['takecode']}
            $packetInfo = $parcelDetail->queryParcelStatus($where);
            if (!empty($packetInfo)) {
                //验证包裹状态
                if ($packetInfo['f_parcel_status'] == 0 || $packetInfo['f_parcel_status'] == 2 || $packetInfo['f_parcel_status'] == 5) {
                    $notice = array(
                        'f_weixin_notice' => 1,
                        'f_weixin_success_time' => date('YmdHis'),
                        'f_weixin_success_time_stamp' => time()
                    );
                    $Notice = new \Home\Server\ParcelNoticeResultServer();
                    $result = $Notice->updateParcelNotice($packetInfo['f_parcel_id'], $notice);
                    if ($result) {
                        $parcelDetail->updateParcel(array('f_parcel_id' => $packetInfo['f_parcel_id']), array('f_parcel_status' => 0, 'f_last_time' => date('YmdHis'), 'f_last_timestamp' => time()));
                        $this->output(true);
                    }
                }
            }
        }

        $this->output(false);
    }

    /**
     * @desc 短信回调
     * @author quyang
     * @update 2016-12-1
     * @again 2017-03-01
     */
    public function setSmsNoticed() {
        $data = I('param.');
        $data = tranSmsStatus($data);
        $status = '2';
        if ($data['status'] == 'DELIVRD') {
            $status = '1';
        }

        if (empty($data['msgid']) && empty($data['status'])) {
            $this->output(false);
        }

        $SmsLog = new \Home\Server\SmsLogServer();
        //查询记录表是否有发送记录
        $logInfo = $SmsLog->queryMsgId($data['msgid']);

        if (is_array($logInfo)) {

            //修改记录状态
            $sms_data = array(
                'f_success_notice' => $data['status'],
                'f_success_time' => date('YmdHis'),
                'f_success_time_stamp' => time()
            );
            $SmsLog->updateSuccessStatus($data['msgid'], $sms_data, $data['table_name']);

            //根据返回状态更改队列发送状态
            $map = array(
                'f_sms_notice' => $status,
                'f_sms_success_time' => date('YmdHis'),
                'f_sms_error' => $data['status'],
                'f_sms_success_time_stamp' => time()
            );
            $Notice = new \Home\Server\ParcelNoticeResultServer();
            $Notice->updateParcelNotice($logInfo['f_parcel_id'], $map);

            //根据发送类型判断是否修改包裹数据   12-22
            if ($logInfo['f_send_sms_type'] == '0') {

                //判断是普通版修改包裹数据
                if ($logInfo['f_type'] == 'DX') {
                    //根据包裹状态为发送中或发送失败时进行修改包裹状态  12-29
                    $where = " `f_parcel_id` = {$logInfo['f_parcel_id']} ";
                    $parcelDetail = new \Home\Server\QueryParcelService();
                    $list = $parcelDetail->queryParcelStatus($where);
                    if ($list['f_parcel_status'] == '2' || $list['f_parcel_status'] == '5') {
                        //根据发送状态更改包裹到站状态
                        if ($status == '1') {
                            $parcelDetail->updateParcel(array('f_parcel_id' => $logInfo['f_parcel_id']), array('f_parcel_status' => 0));
                        } else {
                            $parcelDetail->updateParcel(array('f_parcel_id' => $logInfo['f_parcel_id']), array('f_parcel_status' => 5));  //发送失败  12-23
                        }
                    }
                }
            }
        }

        // 通知失败 启用备用短信接口重发
        if($status == 2){
            // 查询当前包裹失败次数
            $count = $SmsLog->queryFailCount($logInfo['f_parcel_id']) ;
            $res=$Notice->queryParcelNotice($logInfo['f_parcel_id'],"f_sms_notice");
            if($count > 0 && $res['f_sms_notice'] == 2){
                
                $spareSms = A('Common');
                $spareSms->repeatSendSms($logInfo['f_parcel_id'] , $count);
            }  
        }
        
    }

    /**
     * @desc: 根据手机号和状态查询包裹
     * @Author: delayhsiao
     * @update: 2016-12-21
     * */
    public function queryParcelByTelAndStatus() {
        $data = I('param.');
        if (empty($data['fRecipientMobile']) || $data['fParcelStatus'] == '') {
            $this->param_error();
        }

        //未提货包裹  0 2 5， 不需要分页, 有多少显示多少
        if ($data['fParcelStatus'] == -250) {
            $page = 1;
            $pageSize = 1000;
        } else {
            $page = intval($data['currentPage']) <= 1 ? 1 : intval($data['currentPage']);
            $pageSize = intval($data['pageSize']) <= 0 ? 10 : intval($data['pageSize']);
        }

        $parcelService = new \Home\Server\ParcelService();

        //时间区域
        $StartTime = date('Y-m', strtotime('-1 month', strtotime(date('Y-m-d', strtotime('-25 day', time()))))) . '-01';
        $EndTime = date('Y-m-d');

        //状态查询
        $fParcelStatusSql = $data['fParcelStatus'] == -250 ? " AND `f_parcel_status` IN ( 0,2,5 )" : " AND `f_parcel_status` = '{$data['fParcelStatus']}'";

        //获取三个月之内的数据
        $packetInfoList = $parcelService->getConditionTable_Result(
                        $StartTime, $EndTime, "
                                                    `f_parcel_id` AS `parcelID`,
                                                    `f_station_id`,
                                                    `f_parcel_status`,
                                                    `f_recipient_mobile`,
                                                    f_mail_no AS fMailNo,
                                                    f_company_name AS fCompanyName,
                                                    f_take_code AS fTakeCode,
                                                    f_num,
                                                    f_last_time AS fLastTime,
                                                    `f_last_timestamp` AS fLastTimestamp,
                                                    FROM_UNIXTIME(
                                                        `f_last_timestamp`,
                                                        '%Y-%m-%d %H:%i:%S'
                                                    ) AS fLastTimeDate
                                                ", "`f_recipient_mobile` = '{$data['fRecipientMobile']}'{$fParcelStatusSql}"
                )
                ->field("`temp_parcel_info`.*, `tp_user`.`f_user_mobile` AS `fUserMobile`, `tp_user`.`f_address` AS `fAddress`,`tp_user`.`f_professional`")
                ->JOIN("`tp_user` ON `tp_user`.`f_user_id` = `temp_parcel_info`.`f_station_id`")
                ->order('`parcelID` DESC')
                ->page($page, $pageSize)
//                                            ->buildSql()
                ->select()
        ;
//        echo $packetInfoList;exit;

        foreach ($packetInfoList as &$res) {
            if ($res['f_professional'] == 1) {
                $res['fTakeCode'] = $res['f_num'] . '(包裹编号)';
            }
        }

        $return = array(
            'totalRows' => $totalRows,
            'totalPages' => $totalPages,
            'currentPage' => $page,
            'parcelInfoList' => $packetInfoList
        );

        $this->output(true, $return);
    }

    /**
     * @desc: 微信自助提货
     * @Author: delayhsiao
     * @again quyang 2017-1-21
     * @update: 2016-12-21
     *
     * upDate: 黄盖 2017-2-16 15
     * */
    public function queryUpdateParcelStatus() {
        $data = I('param.');
        if (empty($data['fMailNo']) || empty($data['fRecipientMobile'])) {
            $this->param_error();
        }
        $parcelDetail = new \Home\Server\QueryParcelService();

        //时间区域
        $StartTime = date('Y-m', strtotime('-1 month', strtotime(date('Y-m-d', strtotime('-25 day', time()))))) . '-01';
        $EndTime = date('Y-m-d');

        //获取三个月之内的数据
        $result = $parcelDetail->getConditionTable_Result(
                        $StartTime, $EndTime, "
                                                    *
                                                ", "`f_mail_no` = '{$data['fMailNo']}' AND `f_recipient_mobile` = '{$data['fRecipientMobile']}'"
                )
                ->field("`temp_parcel_info`.*, `tp_user`.`f_address`, `tp_user`.`f_store_time`, `tp_user`.`f_user_mobile`, `tp_user`.`f_station_name`")
                ->JOIN("`tp_user` ON `tp_user`.`f_user_id` = `temp_parcel_info`.`f_station_id`")
                ->order('f_parcel_id DESC')
                ->limit(1)
//                                            ->buildSql()
                ->find()
        ;

        //当前包裹状态
        $tip = $result['f_parcel_status'];

//		$where = " `f_mail_no`={$data['fMailNo']} and `f_recipient_mobile` = {$data['fRecipientMobile']} ";
//        $result = $parcelDetail->queryParcelStatus($where);
        //扫码取件, 状态025 可取
        if ($result['f_parcel_status'] == '1' || $result['f_parcel_status'] == '0' || $result['f_parcel_status'] == '2' || $result['f_parcel_status'] == '5') {
            $parcelInfo = $result;
//            print_r( $parcelDetail->reSendParcelDetails($result['f_parcel_id']) );exit;

            if ($result['f_parcel_status'] == '0' || $result['f_parcel_status'] == '2' || $result['f_parcel_status'] == '5') {
//                $parcelDetail->updateParcel(array('f_parcel_id' => $result['f_parcel_id']),);

                $Updata = Array(
                    'f_parcel_status' => 1,
                    'f_last_time' => date('YmdHis'),
                    'f_last_timestamp' => time(),
                    'f_out_time' => date('YmdHis'),
                    'f_out_timestamp' => time(),
                    'f_out_way' => 5, //出库平台  1 IOS  2 Andoird  3 PC  5 微信
                    'f_out_source' => 8                 //出库方式  1 提货码  6 超级密码  7 专业版  8 微信扫码
                );

                ( new \Think\Model())->table($result['table_name'])->where("`f_parcel_id` = {$result['f_parcel_id']}")->save($Updata);


                $parcelInfo['f_parcel_status'] = $Updata['f_parcel_status'];
                $parcelInfo['f_last_time'] = $Updata['f_last_time'];
                $parcelInfo['f_last_timestamp'] = $Updata['f_last_timestamp'];
            }

            //包裹提货时判断队列表包裹发送状态。如果不是成功则改为发送成功  12-30
//            $res = D('Home/ParcelNoticeResult')->where(array('f_mail_no'=>$data['fMailNo']))->find();
            $Notice = new \Home\Server\ParcelNoticeResultServer();
            $res = $Notice->queryParcelNotice($result['f_parcel_id']);


            if ($res['f_weixin_notice'] != '1' && $res['f_weixin_notice'] != '') {
                $Notice->updateParcelNotice($result['f_parcel_id'], ['f_weixin_notice' => '1'], $res['table_name']);
            }

            $return = array(
                'a' => 0,
                'm' => '操作成功',
                'success' => true,
                'd' => array(
                    'tip' => $tip == 1 ? 1 : 0,
                    'parcelInfo' => $parcelInfo
                )
            );
        } else {
            $return = array(
                'a' => 1,
                'm' => '操作失败',
                'success' => false,
                'd' => array(
                    'tip' => 3
                )
            );
        }
        $this->ajaxReturn($return);
    }

    /**
     * @desc:  获取运单信息详情
     * @Author: zhoutai
     * @again quyang 2017-1-21
     * @update: 16/12/24
     * */
    public function queryMailNoInfo() {
        $data = I('param.');
        if (empty($data['parcelId']))
            $this->param_error();

        //获取包裹详情
        $parcelDetail = new \Home\Server\QueryParcelService();

        $result = $parcelDetail->queryParcelDetails($data['parcelId'], $data['date']);

//        dump($result);exit;

        if (empty($result))
            $this->output(0);
        if (stripos($result['fSmsContent'], $result['fTakeCode'], 0) !== false) {
            $result['fSmsContent'] = str_replace($result['fTakeCode'], "******", $result['fSmsContent']);
        }
        $result['fArriveTime'] = date('Y-m-d H:i:s', strtotime($result['fArriveTime']));
        if (!empty($result['fLastTime'])) {
            $result['fLastTime'] = date('Y-m-d H:i:s', strtotime($result['fLastTime']));
        }
        if (!empty($result['fWeixinSendTime'])) {
            $result['fWeixinSendTime'] = date('Y-m-d H:i:s', strtotime($result['fWeixinSendTime']));
        }
        if (!empty($result['fWeixinSuccessTime'])) {
            $result['fWeixinSuccessTime'] = date('Y-m-d H:i:s', strtotime($result['fWeixinSuccessTime']));
        }
        if (!empty($result['fSmsSendTime'])) {
            $result['fSmsSendTime'] = date('Y-m-d H:i:s', strtotime($result['fSmsSendTime']));
        }
        if (!empty($result['fSmsSuccessTime'])) {
            $result['fSmsSuccessTime'] = date('Y-m-d H:i:s', strtotime($result['fSmsSuccessTime']));
        }
        if ($result['fComment'] == null) {
            $result['fComment'] = "";
        }
        $result['fWeixinNotice'] = $result['fWeixinNotice'] == null ? "0" : $result['fWeixinNotice'];
        if ($result['fWeixinNotice'] != '0' && !empty($result['fWeixinNotice'])) {
            $result['weixinSendDate'] = date('m月d日', strtotime($result['fWeixinSendTime']));
        } else {
            $result['weixinSendDate'] = date('m月d日', time());
        }
        switch ($result['fSmsError']) {
            case "B":
                $result['fSmsError'] = "余额不足";
                break;
            case "C":
                $result['fSmsError'] = "提交失败";
                break;
            case "D":
                $result['fSmsError'] = "短信模板获取失败";
                break;
            case "E":
                $result['fSmsError'] = "短信模板替换失败";
                break;
            case "0":
                $result['fSmsError'] = "提交成功";
                break;
            case "DELIVRD":
                $result['fSmsError'] = "发送成功";
                break;
            case null:
                $result['fSmsError'] = null;
                break;
            default:
                $result['fSmsError'] = "发送失败";
                break;
        }
        $result['WeixinHtml'] .= '<div style="font-size:16px;font-weight:700;">快递自提通知</div>';
        $result['WeixinHtml'] .= '<div style="font-size:16px;color:#666">' . $result['weixinSendDate'] . '</div>';
        $result['WeixinHtml'] .= '<div style="height:20px"></div>';
        $result['WeixinHtml'] .= '<div style="font-size:16px;color:#666;">亲，您的包裹已到' . $result['fStationName'] . '</div>';
        $result['WeixinHtml'] .= '<div style="height:20px"></div>';
        $result['WeixinHtml'] .= '<div style="font-size:16px;color:#666"><span style="color:#000;">运单号：</span>' . $result['fMailNo'] . '</div>';
        $result['WeixinHtml'] .= '<div style="font-size:16px;color:#666"><span style="color:#000;">快递公司：</span>' . $result['fCompanyName'] . '</div>';
        $result['WeixinHtml'] .= '<div style="font-size:16px;color:#666"><span style="color:#000;">提货码：</span>******</div>';
        $result['WeixinHtml'] .= '<div style="font-size:16px;color:#666"><span style="color:#000;">地址：</span>' . $result['fAddress'] . '</div>';
        $result['WeixinHtml'] .= '<div style="font-size:16px;color:#666"><span style="color:#000;">取件时间：</span>' . $result['fQtime'] . '</div>';
        $result['WeixinHtml'] .= '<div style="height:20px"></div>';
        $result['WeixinHtml'] .= '<div style="font-size:16px;color:#666">请尽快至站点取货，联系电话：' . $result['fTel'] . '</div>';
        foreach ($result as $k => $v) {
            if ($v == null) {
                $result[$k] = "";
            }
        }
        $this->output(1, $result);
    }

    /**
     * @desc:  获取运单信息详情
     * @Author:
     * @again
     * */
    public function queryMailDetail() {
        $data = I('param.');
        if (empty($data['parcelId']) || empty($data['data']))
            $this->param_error();

        //获取包裹详情
        $parcelDetail = new \Home\Server\QueryParcelService();

        $result = $parcelDetail->queryParcelDetailsForPacket($data['parcelId'], $data['data']);

        if (empty($result))
            $this->output(0,'','未查询到包裹数据');

        // 获取联系人默认标签
        $mobileModel = new \Home\Model\MobileInfoModel();
        $label = $mobileModel -> querySendLabel($result['fStationId'] ,$result['fRecipientMobile']);


        // 拼接数据
        switch ($result['fParcelStatus'])
        {
            case 0:
                $res['status'] = '已到站';
                break;
            case 1:
                $res['status'] = '已提货';
                break;
            case 2:
                $res['status'] = '通知中';
                break;
            case 3:
                $res['status'] = '异常件';
                break;
            case 4:
                $res['status'] = "拒收件（{$result['fComment']}）";
                break;
            case 5:
                $res['status'] = '通知失败';
                break;
            case 6:
                $res['status'] = "拒收出库（{$result['fComment']}）";
                break;
        }


        $res['fCompanyName'] = $result['fCompanyName'];
        $res['fArriveTime'] = $result['fArriveTime'];
        $res['noticeTime'] = !empty($result['fWeixinSendTime']) ? $result['fWeixinSendTime'] : $result['fSmsSendTime'];
        $res['fOutTime'] = !empty($result['fOutTime']) ? $result['fOutTime'] : '';
        $res['fNum'] = $result['fNum'];
        $res['fMailNo'] = $result['fMailNo'];
        $res['fRecipientName'] = $result['fRecipientName'];
        $res['fRecipientMobile'] = $result['fRecipientMobile'];
        $res['fComment'] = $result['fComment'];
        $res['fParcelStatus'] = $result['fParcelStatus'];

        if ($label['f_receive_label_id'])
        {
            $res['fReceiveLabelId'] = $label['f_receive_label_id'];
        }
        else
        {
            $res['fReceiveLabelId'] = 100;
        }


        $res['fArriveTime'] = date('Y-m-d H:i:s', strtotime($res['fArriveTime']));

        if (!empty($res['noticeTime'])) {
            $res['noticeTime'] = date('Y-m-d H:i:s', strtotime($res['noticeTime']));
        }
        if (!empty($res['fOutTime'])) {
            $res['fOutTime'] = date('Y-m-d H:i:s', strtotime($res['fOutTime']));
        }
        if ($result['fWeixinNotice'] == 1 )
        {
            $res['noticeList'][] = array('title' => '到站通知（成功）' ,'value' => date('Y-m-d H:i:s', strtotime($result['fWeixinSuccessTime'])),'type' => 1);
        }
        elseif ($result['fSmsNotice'] == 1)
        {
            $res['noticeList'][] = array('title' => '到站通知（成功）' ,'value' => date('Y-m-d H:i:s', strtotime($result['fSmsSuccessTime'])),'type' => 2);

        }
        elseif ($result['fWeixinNotice'] == 3)
        {
            $res['noticeList'][] = array('title' => '到站通知（通知中）' ,'value' => date('Y-m-d H:i:s', strtotime($result['fWeixinSendTime'])),'type' => 1);
        }
        elseif ($result['fSmsNotice'] == 3)
        {
            $res['noticeList'][] = array('title' => '到站通知（通知中）' ,'value' => date('Y-m-d H:i:s', strtotime($result['fSmsSendTime'])),'type' => 2);
        }
        elseif ($result['fWeixinNotice'] == 2)
        {
            $res['noticeList'][] = array('title' => '到站通知（失败）' ,'value' => date('Y-m-d H:i:s', strtotime($result['fWeixinSendTime'])),'type' => 1);
        }
        elseif ($result['fSmsNotice'] == 2)
        {
            $res['noticeList'][] = array('title' => '到站通知（失败）' ,'value' => date('Y-m-d H:i:s', strtotime($result['fSmsSendTime'])),'type' => 2);
        }
        // 获取重发信息
//        $tableTime = substr($result['table_name'] , -6 ,6);
        $tableTime = 'tp_sms_log_'.$data['data'];


        $where['f_station_id'] = $result['fStationId'];
        $where['f_parcel_id'] = $result['fParcelId'];
        $where['f_send_sms_type'] = 1;

        $logData = D() -> table($tableTime) ->where($where) -> order('f_send_time_stamp desc') -> select();


        foreach ($logData as $lkey => $lval)
        {
            $res['noticeList'][] = array('title' => '重发通知' ,'value' => date('Y-m-d H:i:s', $logData[$lkey]['f_send_time_stamp']) ,'type' => 2);
        }

        $this->output(1, $res);
    }

    /**
     * @desc: 根据手机号和状态和站点id查询包裹（第三方合作站点用到）
     * @Author: cheng 复制修改
     * @update: 2017-06-21
     * */
    public function queryParcelYjl() {
        $params = $_REQUEST['params'];
        $data = json_decode($params, TRUE);
        if (empty($data['fRecipientMobile']) || $data['fParcelStatus'] == '' || $data['fStationId'] == '' || $data['fPartnerCode'] == '') {
            $this->yjlParamError();
        }
        //验证第三方合作站点代码号
        $f_partner_code = M('tp_third_partner')->where(['f_station_id' => $data['fStationId']])->getField('f_partner_code');
        $data['fPartnerCode'] != $f_partner_code && $this->yjlParamError($info = '合作站点代码校验错误');

        ////未提货包裹  0 2 5， 不需要分页, 有多少显示多少
        //if ($data['fParcelStatus'] == -250) {
            //$page = 1;
            //$pageSize = 1000;
        //} else {
            //$page = intval($data['currentPage']) <= 1 ? 1 : intval($data['currentPage']);
            //$pageSize = intval($data['pageSize']) <= 0 ? 10 : intval($data['pageSize']);
        //}
        $page = intval($data['currentPage']) <= 1 ? 1 : intval($data['currentPage']);
        $pageSize = intval($data['pageSize']) <= 0 ? 10 : intval($data['pageSize']);

        $parcelService = new \Home\Server\ParcelService();

        //时间区域
        $StartTime = date('Y-m', strtotime('-1 month', strtotime(date('Y-m-d', strtotime('-25 day', time()))))) . '-01';
        $EndTime = date('Y-m-d');

        //状态查询
        $fParcelStatusSql = $data['fParcelStatus'] == -250 ? " AND `f_parcel_status` IN ( 0,2,5 )" : " AND `f_parcel_status` = '{$data['fParcelStatus']}'";
        
        //站点id查询
        $fStationSql = " AND `f_station_id` = '{$data['fStationId']}'";

        //获取三个月之内的数据
        $packetInfoList = $parcelService->getConditionTable_Result(
                        $StartTime, $EndTime,
                        "f_parcel_id AS parcelID,
                        f_station_id,
                        f_parcel_status,
                        f_recipient_mobile,
                        f_mail_no AS fMailNo,
                        f_company_name AS fCompanyName,
                        f_take_code AS fTakeCode,
                        f_num,
                        f_last_time AS fLastTime,
                        f_last_timestamp AS fLastTimestamp,
                        FROM_UNIXTIME(
                            `f_last_timestamp`,
                            '%Y-%m-%d %H:%i:%S'
                        ) AS fLastTimeDate", 
                        "f_recipient_mobile = '{$data['fRecipientMobile']}'{$fStationSql}{$fParcelStatusSql}"
                )
                ->field("`temp_parcel_info`.*, `tp_user`.`f_user_mobile` AS `fUserMobile`, `tp_user`.`f_address` AS `fAddress`,`tp_user`.`f_professional`")
                ->JOIN("`tp_user` ON `tp_user`.`f_user_id` = `temp_parcel_info`.`f_station_id`")
                ->order('`parcelID` DESC')
                ->page($page, $pageSize)
                ->select();
        $totalRows = $parcelService->getConditionTable_Result(
                        $StartTime, $EndTime,
                        "f_parcel_id AS parcelID,
                        f_station_id,
                        f_parcel_status,
                        f_recipient_mobile,
                        f_mail_no AS fMailNo,
                        f_company_name AS fCompanyName,
                        f_take_code AS fTakeCode,
                        f_num,
                        f_last_time AS fLastTime,
                        f_last_timestamp AS fLastTimestamp,
                        FROM_UNIXTIME(
                            `f_last_timestamp`,
                            '%Y-%m-%d %H:%i:%S'
                        ) AS fLastTimeDate", 
                        "f_recipient_mobile = '{$data['fRecipientMobile']}'{$fStationSql}{$fParcelStatusSql}"
                )
                ->field("`temp_parcel_info`.`f_station_id`")
                ->join("`tp_user` ON `tp_user`.`f_user_id` = `temp_parcel_info`.`f_station_id`")
                ->count();

        //foreach ($packetInfoList as &$res) {
            //if ($res['f_professional'] == 1) {
                //$res['fTakeCode'] = $res['f_num'] . '(包裹编号)';
            //}
        //}

        $return = array(
            'totalRows' => $totalRows,
            'totalPages' => ceil($totalRows / $pageSize),
            'currentPage' => $page,
            'parcelInfoList' => $packetInfoList
        );

        $this->yjlOutPut(true, $return);
    }

}
